<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Org;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopjoin;
use app\admin\model\Shopmno;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Tuan extends Api
{
    protected $noNeedLogin = ['wechatNotify','sxfCallback'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function detail(){

        $id = $this->request->param('id');
        $shopTuanModel = new Shoptuan();
        $tuan = $shopTuanModel->where('id',$id)->find();

        $rule = json_decode($tuan['rule'],true);
        $ruleTxt = explode(",",$tuan['rule_txt']);
        $tuan['time'] =$rule['time'];

        $week = $rule['week'];
        $s = "";
        foreach ($week as $key=>$val){
            if($val  == 1){
                $s  = $s."周一,";
            }else if($val == 2){
                $s  = $s."周二,";
            }else if($val == 3){
                $s  = $s."周三,";
            }else if($val == 4){
                $s  = $s."周四,";
            }else if($val == 5){
                $s  = $s."周五,";
            }else if($val == 6){
                $s  = $s."周六,";
            }else if($val == 7){
                $s  = $s."周日";
            }
        }




       $discount =  formatMoney($tuan['line_price']-$tuan['price']);
        if($discount <0) $discount = 0;

        $ruleStr = "";
        foreach ($ruleTxt as $key=>$val){

            if($key != count($ruleTxt)-1){
                $ruleStr = $ruleStr.$val."," ;
            }
        }

        $tuan['discount'] = $discount;
        $tuan['rule_txt'] = $ruleStr;

        $shopList = $rule['shop'];
        $shopModel = new Shop();
        $roomModel = new Shoproom();
        $roomList = array();
        foreach ($shopList as $key=>$val){

            $shopId = $val['shop_id'];
            $rooms = $val['room'];
            $shop = $shopModel->where('id',$shopId)->find();
            foreach ($rooms as $k=>$v){
               $room =  $roomModel->where('id',$v)->find();
               $name = "【".$shop['name'].'-'.$room['name']."】";
                $roomList[] = $name;
            }
        }

        $tuan['week'] = $s;
        $tuan['room'] = $roomList;

        $this->success('',$tuan);
    }


    public function refund(){

        $id = $this->request->param('id');
        $userTuanModel = new Usertuan();
        $tuan = $userTuanModel->where('id',$id)->find();
        if($tuan['status'] == 'used') $this->error("此券已用 不能退款");
        $tuanOrderModel = new Tuanorder();
        $order = $tuanOrderModel->where('id',$tuan['order_id'])->find();
        $refundOrder_no = getOrderSn();
        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();
        $mno = $org['mno'];
        $shopMnoModel =new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id',$order['shop_id'])->find();
        if($shopMno && $shopMno['ratio'] == 100){
            $mno = $shopMno['mno'];
        }
        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = $refundOrder_no;
        $req['origOrderNo'] = $order['order_no'];
        $req['amt'] = $order['amount'];

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $result = json_decode($ret, true);
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        $tuanOrderModel->where('id',$order['id'])->update(['status'=>'refund']);

        $userTuanModel->where('id',$id)->update(['status'=>'refund']);

        $shopOrderProfitModel = new Shoporderprofit();
        $shopOrderProfitModel->where('order_id',$order['id'])->where('type','tuan')->delete();
        $this->success("成功");
    }

    public function getList(){

        $shop_id = $this->request->param('shop_id');
        $page = $this->request->param('page');

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['shop_id'] = $shop_id;

        $shopTuanModel = new Shoptuan();
        $list = $shopTuanModel->where($where)->where('status',"<>",-1)->order('create_time','desc')->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){
           $list[$key]['check'] = false;
           $tag =  explode("|",$val['rule_txt']);
           $tags = array();
           foreach ($tag as $k=>$v){
               $obj = array();
               $obj['id'] = ($k+1);
               $obj['value'] = $v;
               $tags[] = $obj;
           }
           $list[$key]['rule_txt'] = $tags;
        }

        $this->success('',$list);

    }

    public function lookRoom(){
        $id = $this->request->param('id');
        $shopTuanModel = new Shoptuan();
        $shopModel = new Shop();
        $roomModel = new Shoproom();
        $tuan = $shopTuanModel->where('id',$id)->find();
        if($tuan){

           $rule = json_decode($tuan['rule'],true);
           $shopList = $rule['shop'];
           $list = array();
           foreach ($shopList as $key=>$val){
             $shop_id =   $val['shop_id'];
             $room = $val['room'];
             $obj = array();
             $shop = $shopModel->where('id',$shop_id)->find();
             $obj['shopName'] = $shop['name'];

             $roomList = array();
             foreach ($room as $k=>$v){
                 $rObj = array();
                 $r =  $roomModel->where('id',$v)->find();
                 $rObj['name'] = $r['name'];
                 $roomList[] = $rObj;
             }
               $obj['room'] = $roomList;

               $list[] = $obj;
           }
           $this->success('',$list);
        }else{
            $this->error("不存在或者已过期");
        }

    }

    public function addTuanOrder(){

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopTuanModel = new Shoptuan();
        $tuan = $shopTuanModel->where('id',$id)->find();
        $orgId = $this->request->param('orgId');

        error_log("=====orgId===".$orgId);
        if(!$orgId){
            $shopModel = new Shop();
            $shop = $shopModel->where('id',$tuan['shop_id'])->find();
            $orgId = $shop['org_id'];
        }

        $usertuanModel = new Usertuan();
        $total = $usertuanModel->where('user_id',$user['id'])->where('tuan_id',$id)->count('id');
        if($total >= $tuan['is_max_buy']){
            $this->error("一个用户只能买".$tuan['is_max_buy']."张");

        }
        if($tuan['status'] == 1){

            $order_no = getOrderSn();
            $db = array();
            $db['user_id'] = $user['id'];
            $db['order_no'] = $order_no;
            $db['create_time'] = time();
            $db['tuan_id'] = $id;
            $db['shop_id'] = $tuan['shop_id'];

            $db['amount'] = $tuan['price'];
            $db['org_id']  =  $orgId;


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $tuan['shop_id'])->find();


            $db['pay_rate'] =formatMoney($shop['pay_rate']*  $db['amount']/100);
            $db['rate'] =formatMoney($shop['ratio']* $db['amount']/100);




            $tuanOrderModel = new Tuanorder();

            $id = $tuanOrderModel->insertGetId($db);
            if ($id > 0) {

                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//
//                $params = [
//                    'out_trade_no' => $order_no,//你的订单号
//                    'total_fee' => $tuan['price'] * 100,//单位元
//                    'body' => $tuan['name'] . "券购买",
//                    'openid' => $wx['openid'],
//
//                ];
//
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/tuan/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//                $info = array();
//                $info['order_no'] = $order_no;
//                $info['payInfo'] = json_decode($result, true);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/tuan/sxfCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();
                $req['mno'] = $org['mno'];//纷享未来药房
                $req['ordNo'] = $order_no;
                $req['amt'] =  $tuan['price'];

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = $tuan['name'] . "券购买";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                error_log("=====ret===".json_encode($req));

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];
                    $this->success('下单成功', $info);

                } else {
                    $this->error($bizMsg);
                }


            }else{
                $this->error("订单生成失败,请联系客服");
            }

        }else{
            $this->error("该券已下架");
        }

    }

    public function addTuanOrderFz(){

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopTuanModel = new Shoptuan();
        $tuan = $shopTuanModel->where('id',$id)->find();
        $orgId = $this->request->param('orgId');

        error_log("=====orgId===".$orgId);
        if(!$orgId){
            $shopModel = new Shop();
            $shop = $shopModel->where('id',$tuan['shop_id'])->find();
            $orgId = $shop['org_id'];
        }

        $usertuanModel = new Usertuan();
        $total = $usertuanModel->where('user_id',$user['id'])->where('tuan_id',$id)->count('id');
        if($total >= $tuan['is_max_buy']){
            $this->error("一个用户只能买".$tuan['is_max_buy']."张");

        }
        if($tuan['status'] == 1){

            $order_no = getOrderSn();
            $db = array();
            $db['user_id'] = $user['id'];
            $db['order_no'] = $order_no;
            $db['create_time'] = time();
            $db['tuan_id'] = $id;
            $db['shop_id'] = $tuan['shop_id'];

            $db['amount'] = $tuan['price'];
            $db['org_id']  =  $orgId;


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $tuan['shop_id'])->find();
            if($orgId == ""){
                $orgId = $shop['org_id'];
            }


            $db['pay_rate'] =formatMoney($shop['pay_rate']*  $db['amount']/100);
            $db['rate'] =formatMoney($shop['ratio']* $db['amount']/100);




            $tuanOrderModel = new Tuanorder();

            $id = $tuanOrderModel->insertGetId($db);
            if ($id > 0) {

                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//
//                $params = [
//                    'out_trade_no' => $order_no,//你的订单号
//                    'total_fee' => $tuan['price'] * 100,//单位元
//                    'body' => $tuan['name'] . "券购买",
//                    'openid' => $wx['openid'],
//
//                ];
//
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/tuan/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//                $info = array();
//                $info['order_no'] = $order_no;
//                $info['payInfo'] = json_decode($result, true);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/tuan/sxfCallback";


                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();


                $shopMnoModel =new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
                $mno = $org['mno'];
                if($shopMno){
                    if($shopMno['ratio'] == 100){
                        //走挂靠
                        $mno = $shopMno['mno'];
                    }else{
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

                        $pay_price = $tuan['price'];
                        $realPay = $pay_price- $pay_price*0.006;
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }


                $req['mno'] = $mno;

                error_log("===addTuanFz===".json_encode($req));

                $req['ordNo'] = $order_no;
                $req['amt'] =  $tuan['price'];

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = $tuan['name'] . "券购买";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                error_log("=====ret===".json_encode($req));

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];
                    $this->success('下单成功', $info);

                } else {
                    $this->error($bizMsg);
                }


            }else{
                $this->error("订单生成失败,请联系客服");
            }

        }else{
            $this->error("该券已下架");
        }

    }



    public function addTuanOrderFzMore(){

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopTuanModel = new Shoptuan();
        $tuan = $shopTuanModel->where('id',$id)->find();
        $orgId = $this->request->param('orgId');


        $usertuanModel = new Usertuan();
        $total = $usertuanModel->where('user_id',$user['id'])->where('tuan_id',$id)->count('id');
        if($total >= $tuan['is_max_buy']){
            $this->error("一个用户只能买".$tuan['is_max_buy']."张");

        }
        if($tuan['status'] == 1){

            $order_no = getOrderSn();
            $db = array();
            $db['user_id'] = $user['id'];
            $db['order_no'] = $order_no;
            $db['create_time'] = time();
            $db['tuan_id'] = $id;
            $db['shop_id'] = $tuan['shop_id'];

            $db['amount'] = $tuan['price'];
            $db['org_id']  =  $orgId;


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $tuan['shop_id'])->find();
            if($orgId == ""){
                $orgId = $shop['org_id'];
            }


            $db['pay_rate'] =formatMoney($shop['pay_rate']*  $db['amount']/100);
            $db['rate'] =formatMoney($shop['ratio']* $db['amount']/100);




            $tuanOrderModel = new Tuanorder();

            $id = $tuanOrderModel->insertGetId($db);
            if ($id > 0) {

                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//
//                $params = [
//                    'out_trade_no' => $order_no,//你的订单号
//                    'total_fee' => $tuan['price'] * 100,//单位元
//                    'body' => $tuan['name'] . "券购买",
//                    'openid' => $wx['openid'],
//
//                ];
//
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/tuan/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//                $info = array();
//                $info['order_no'] = $order_no;
//                $info['payInfo'] = json_decode($result, true);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/tuan/sxfCallback";


                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();


                $shopMnoModel =new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
                $mno = $org['mno'];
                if($shopMno){
                    if($shopMno['ratio'] == 100){
                        //走挂靠
                        $mno = $shopMno['mno'];
                    }else{
                        //走分账

                        $pay_price = $tuan['price'];

                        $listMnos = $shopMnoModel->where('shop_id',$shop['id'])->select();
                        $fs = array();
                        $realPay = formatMoney($pay_price- $pay_price*0.006);
                        foreach ($listMnos as $key=>$val){
                            //走分账
                            $fusruleId = array();
                            $fusruleId['mno'] = $val['mno'];
                            $fusruleId['allotValue'] = formatMoney($val['ratio']*$realPay/100);
                            $fs[] = $fusruleId;

                        }

                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;

                $req['ordNo'] = $order_no;
                $req['amt'] =  $tuan['price'];

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = $tuan['name'] . "券购买";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                error_log("=====ret===".json_encode($req));

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $order_no;
                    $info['payInfo'] = $result['respData'];
                    $this->success('下单成功', $info);

                } else {
                    $this->error($bizMsg);
                }


            }else{
                $this->error("订单生成失败,请联系客服");
            }

        }else{
            $this->error("该券已下架");
        }

    }


    public function sxfCallback(){

        $param = file_get_contents("php://input");
        error_log("===order===callback=====" . json_encode($param));

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $tuanOrderModel = new Tuanorder();
            $order = $tuanOrderModel->where('order_no', $out_trade_no)->find();
            $tuanOrderModel->where('id',$order['id'])->update(['status'=>'payed']);
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id',$order['tuan_id'])->find();
            $endTime = strtotime("+".$tuan['valid_day']." day",time());
            $userTuanModel = new Usertuan();


            /**
             * 商家分润
             */
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id',$tuan['shop_id'])->find();

            $shopOrderProfitModel  = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$tuan['shop_id'],'type'=>'tuan',
                'user_id'=>$shop['user_id'],'create_time'=>time(),'amount'=>formatMoney(($order['amount']-$order['rate']-$order['pay_rate']))]);

            /**
             * 代理商分润
             */
            if($shop['agent_ratio'] > 0){

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio']*$order['amount']/100;
                if($agentFee >0){
                    $userOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$tuan['shop_id'],'type'=>'tuan',
                        'user_id'=>$shop['agent_id'],'create_time'=>time(),'amount'=>formatMoney($agentFee)]);

                }

            }
            $userTuanModel->insert(['user_id'=>$order['user_id'],'valid_time'=>$endTime,'status'=>'unuse','tuan_id'=>$order['tuan_id'],'create_time'=>time(),'order_id'=>$order['id']]);
        }
    }


    public function wechatNotify()
    {

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {

            $tuanOrderModel = new Tuanorder();
            $order = $tuanOrderModel->where('order_no', $out_trade_no)->find();
            $tuanOrderModel->where('id',$order['id'])->update(['status'=>'payed']);
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id',$order['tuan_id'])->find();
            $endTime = strtotime("+".$tuan['valid_day']." day",time());
            $userTuanModel = new Usertuan();


            /**
             * 商家分润
             */
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id',$tuan['shop_id'])->find();

            $shopOrderProfitModel  = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$tuan['shop_id'],'type'=>'tuan',
                'user_id'=>$shop['user_id'],'create_time'=>time(),'amount'=>formatMoney(($order['amount']-$order['rate']-$order['pay_rate']))]);

            /**
             * 代理商分润
             */
            if($shop['agent_ratio'] > 0){

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio']*$order['amount']/100;
                if($agentFee >0){
                    $userOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$tuan['shop_id'],'type'=>'tuan',
                        'user_id'=>$shop['agent_id'],'create_time'=>time(),'amount'=>formatMoney($agentFee)]);

                }

            }



            $userTuanModel->insert(['user_id'=>$order['user_id'],'valid_time'=>$endTime,'status'=>'unuse','tuan_id'=>$order['tuan_id'],'create_time'=>time(),'order_id'=>$order['id']]);
        }
        return $pay->success();

    }

    public function userTuanList(){

        $user = $this->auth->getUser();
        $userTuanModel = new Usertuan();
        $list= $userTuanModel->with(['tuan'])->where('user_id',$user['id'])->where('Usertuan.status','unuse')->select();
        foreach ($list as $key=>$val){
            $end = strtotime("+".$val['tuan']['valid_day']." day",$val['create_time']);
            $list[$key]['end'] = date("Y-m-d",$end);
            $list[$key]['check'] = false;
            $tag =  explode("|",$val['tuan']['rule_txt']);
            $tags = array();
            foreach ($tag as $k=>$v){
                $obj = array();
                $obj['id'] = ($k+1);
                $obj['value'] = $v;
                $tags[] = $obj;
            }
            $list[$key]['rule'] = $tags;

        }
        $this->success('',$list);
    }



}
